import random

from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.
from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from rest_framework.views import APIView

from celery_tasks.sms.tasks import send_sms_code
from meiduo_shop.libs.captcha.captcha import captcha
from meiduo_shop.libs.yuntongxun.sms import CCP
from users.models import User
from verifications import constants
from verifications.serializers import ImageCodeSerializer
import logging

logger = logging.getLogger('django')

class ImageCodeView(APIView):
    """
    图片验证码
    """

    def get(self, request, image_code_id):
        """获取图片验证码"""
        text, image = captcha.generate_captcha()
        print('图片验证码[调试信息]: {}\n'.format(text))
        redis_con = get_redis_connection('verify')
        redis_con.setex('image_code_%s'%image_code_id, constants.IMAGE_CODE_REDIS_EXPIRE, text)
        return HttpResponse(image, content_type='image/jpg')


class SMSCodeView(APIView):
    """短信验证码"""

    def get(self,request,mobile):
        # 1.获取参数
        # 2.校验参数
            # 1.校验参数
            # 2.从redis读取真实图片验证码
            # 3.校验图片验证码
        # 3.判断发送是否在1min钟内
        serializer = ImageCodeSerializer(data=request.query_params,context={'view':self})
        serializer.is_valid(raise_exception=True)

        # 1.生成短信验证码
        sms_code = '%06d'% random.randint(0,99999)
        print('短信验证码[调试信息]: {}\n'.format(sms_code))
        # 2.保存短信验证码
        redis_con = get_redis_connection('verify')
        pl = redis_con.pipeline()
        pl.setex('sms_code_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRE, sms_code)
        # 3.保存短信发送标志
        pl.setex('send_flag_%s' % mobile, constants.SMS_SEND_FLAG_INTERVAL, 1)
        pl.execute()
        # 4.发送短信验证码
        send_sms_code.delay(mobile, sms_code, constants.SMS_CODE_REDIS_EXPIRE//60, constants.SMS_CODE_TEMPLATE_ID)
        # 5.返回响应
        return Response({'message':'OK'})


class UsernameCountView(APIView):

    def get(self,request,username):
        count = User.objects.filter(username__exact=username).count()
        data = {
            'username':username,
            'count': count
        }
        return Response(data)


class MobileCountView(APIView):

    def get(self,request,mobile):
        count = User.objects.filter(mobile__exact=mobile).count()
        data = {
            'mobile': mobile,
            'count': count
        }
        return Response(data)
